<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.title"
          clearable
          placeholder="标题"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.msgContent"
          clearable
          placeholder="内容"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="80%"
        top="10px"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-col :span="24">
            <el-form-item label="标题">
              <el-input v-model="form.title" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="推送方式">
              <el-select v-model="form.pushType" filterable placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in dict.pushType"
                  :key="item.id"
                  :label="item.dictValue"
                  :value="item.dictKey"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="接收人姓名">
              <el-select
                ref="selectDom"
                v-model="form.memberIds"
                filterable
                remote
                multiple
                clearable
                :loading="userLoading"
                :remote-method="remoteGetUser"
                placeholder="请选择用戶"
                style="width: 100%"
              >
                <el-option
                  v-for="item in list"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.pushType === 0" :span="24">
            <el-form-item label="联系號碼">
              <el-input v-model="phoneNum" />
              <el-button type="success" @click="addPhoneNum">添加</el-button>
              <div>
                <el-tag v-for="(item, index) in form.phone" :key="index" closable @close="reducePhone(item)">{{
                  item
                }}
                </el-tag>
              </div>
            </el-form-item>

          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" prop="msgContent">
              <tinymce ref="tinymce" v-model="form.msgContent" :width="900" :height="300" />
            </el-form-item>
          </el-col>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        style="width: 100%;"
        stripe
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="標題" />
        <el-table-column prop="createdAt" label="創建時間" />
        <el-table-column prop="msgContent" label="内容" show-tooltip-when-overflow />
        <el-table-column prop="sender" label="操作人" />
        <el-table-column prop="usernames" label="接收人" show-tooltip-when-overflow />
        <el-table-column prop="pushType" label="推送方式">
          <template slot-scope="scope">
            {{ dict.label.pushType[scope.row.pushType] }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkPer(['admin','memberMessage:edit','memberMessage:del'])"
          label="操作"
          width="150px"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudMemberMessage from '@/api/msg/memberMessage'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import messageTemplate from '@/api/msg/messageTemplate'
import Tinymce from '@/components/Tinymce'
import { page } from '@/api/ums/member'

const defaultForm = {
  title: null,
  msgContent: null,
  memberIds: null,
  usernames: null,
  phone: [],
  pushType: 3
}
export default {
  name: 'ManagerMessage',
  components: { pagination, crudOperation, rrOperation, udOperation, Tinymce },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['pushType'],
  cruds() {
    return CRUD({ title: '消息管理', url: 'sysMessage/page', sort: 'id:desc', crudMethod: { ...crudMemberMessage }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'memberMessage:add'],
        edit: ['admin', 'memberMessage:edit'],
        del: ['admin', 'memberMessage:del']
      },
      rules: {
        msgContent: [
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'title', display_name: '标题' },
        { key: 'msgContent', display_name: '内容' }
      ],
      userList: [],
      userLoading: false,
      list: [],
      msgTemplate: [],
      phoneNum: null
    }
  },
  created() {
    this.getTemplate()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.afterSubmit]() {
      this.$refs.tinymce.setContent('')
      return true
    },
    [CRUD.HOOK.afterEditCancel]() {
      this.$refs.tinymce.setContent('')
      return true
    },
    [CRUD.HOOK.afterToEdit]() {
      if (this.$refs.tinymce) {
        this.$refs.tinymce.setContent(this.form.msgContent || '')
      }
      this.$nextTick(() => {
        this.getOption()
      })
      return true
    },
    getTemplate() {
      messageTemplate.all().then(res => {
        if (res.code === 0) {
          this.msgTemplate = res.data
        }
      })
    },
    remoteGetUser(query) {
      if (query !== '') {
        this.loading = true
        page({ memberName: query, size: 50 }).then(res => {
          if (res.code === 0) {
            this.loading = false
            this.list = res.data.rows
          }
        })
      } else {
        this.list = []
      }
    },
    addPhoneNum() {
      if (!this.form.phone.includes(this.phoneNum)) {
        this.form.phone.push(this.phoneNum)
        this.phoneNum = null
      } else {
        this.$message({
          message: '號碼重複,請重新輸入',
          type: 'warning'
        })
      }
    },
    reducePhone(sel) {
      const numIndex = this.form.phone.indexOf(sel)
      if (numIndex !== -1) {
        this.form.phone.splice(this.form.phone.indexOf(sel), 1)
      }
    },
    getOption() {
      // 解决回显时显示为id的问题
      this.userList.forEach((item) => {
        this.$refs.selectDom.cachedOptions.push({
          currentLabel: item.username,
          currentValue: item.id,
          label: item.username,
          value: item.id
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
